import ExportFormData from '@/components/ExportFormData';
import { QuestionMsg } from '@/components/Question';
import StateTab from '@/components/StateTab';
import { DatePicker, message, Modal, Spin, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import { CurrentUserProps } from '@/types';
import 'react-quill/dist/quill.snow.css';
import { connect } from 'umi';
import { formatYYMMDDHHMM } from '@/utils/timeFormat';
import { ReplyInput } from '@/components/Reply';
import styles from './index.less';
import { cancelReply, getAnswerDetail, getAnswerList, submitReply } from './service';

const { RangePicker } = DatePicker;

let submitTime: string[] = [];
let auditTime: string[] = [];
let selectState = 0;

const Content: React.FC<{ currentUser: CurrentUserProps }> = ({ currentUser }) => {
  const { pid } = currentUser;

  const [loading, setLoading] = useState<boolean>(true);
  const [detailLoading, setDetailLoading] = useState<boolean>(true);

  const [dataSource, setDataSource] = useState<[]>([]);
  const [detailSource, setDetailSource] = useState<{}>({});
  const [pageTotal, setPageTotal] = useState<number>(0);
  const [pageCurrent, setPageCurrent] = useState<number>(1);

  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [modalAuditState, setModalAuditState] = useState<number>(0);

  const [defaultSelect] = useState<number>(currentUser.replyCount ? 4 : 1);

  const [currentDetail, setCurrentDetail] = useState<{}>({});

  const answerListView = async (pageIndex: number = 1, pageSize: number = 10) => {
    setLoading(true);
    setPageCurrent(pageIndex);
    const { code, data, total, info } = await getAnswerList({
      pid,
      type: selectState,
      beginSubTime: submitTime[0],
      endSubTime: submitTime[1],
      beginAuditTime: auditTime[0],
      endAuditTime: auditTime[1],
      pageIndex,
      pageSize,
    });

    setLoading(false);
    if (code != 0) {
      message.error(info);
      return;
    }
    const list = data.map((item: any, index: number) => {
      return {
        key: index,
        handle: item.auditState,
        ...item,
      };
    });

    setDataSource(list);
    setPageTotal(total);
  };

  useEffect(() => {
    if (currentUser.replyCount) {
      selectState = 2;
    }
    answerListView();
  }, []);

  const answerDetailView = async (item: { key: string }) => {
    const { key } = item;
    const { tid, typeId, replyId } = dataSource[key];

    setModalVisible(true);
    setDetailLoading(true);
    const { data } = await getAnswerDetail({ tid, typeId, replyId, web: 1 });
    setDetailLoading(false);
    setDetailSource({ ...data });
  };

  const submitTimeChange = (date: {}[], dateStr: string[]) => {
    submitTime = [...dateStr];
    answerListView();
  };

  const auditTimeChange = (date: {}[], dateStr: string[]) => {
    auditTime = [...dateStr];
    answerListView();
  };

  const cancelEdit = async () => {
    const { replyId } = currentDetail;
    const { code, info } = await cancelReply({ replyId });

    if (code != 0) {
      message.error(info);
      return;
    }
    message.info('已放弃修改');
    setModalVisible(false);
    answerListView();
  };

  const submitEdit = async (replyList) => {
    const { tid, replyId } = currentDetail;
    const { code, info } = await submitReply({ pid, tid, replyId, contentList: replyList });
    if (code != 0) {
      message.error(info);
      return;
    }
    setModalVisible(false);
    answerListView();
  };

  const editHandle = (item) => {
    const { auditState } = item;
    setModalAuditState(auditState);
    setCurrentDetail(item);
    answerDetailView(item);
  };

  const selectTab = ({ state }) => {
    selectState = state;
    answerListView();
  };

  const getStateStr = (state: number): string => {
    /*eslint-disable */
    let str = '';
    state === 1 && (str = '合格');
    state === 4 && (str = '合格');
    state === 2 && (str = '不合格');
    state === 3 && (str = '待审核');
    state === 5 && (str = '已失效');
    return str;
  };

  // 1审核合格，2审核不合格，3待审核，4审核优质，5已失效
  const tabColumns = [
    {
      key: 'title',
      text: '状态',
    },
    {
      key: 'tab',
      text: '全部',
      state: 0,
    },
    {
      key: 'tab',
      text: '待审核',
      state: 3,
    },
    {
      key: 'tab',
      text: '合格',
      state: 1,
    },
    {
      key: 'tab',
      text: '不合格',
      state: 2,
    },
    {
      key: 'tab',
      text: '已失效',
      state: 5,
    },
  ];

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string, item: {}) => (
        <a
          onClick={() => {
            editHandle(item);
          }}
        >
          {text}
        </a>
      ),
    },
    {
      title: '积分',
      dataIndex: 'score',
      key: 'score',
    },
    {
      title: '提交时间',
      dataIndex: 'submitDate',
      key: 'submitDate',
      render: (submitDate: number) => formatYYMMDDHHMM(submitDate),
    },
    {
      title: '审核时间',
      dataIndex: 'auditDate',
      key: 'auditDate',
      render: (auditDate) => formatYYMMDDHHMM(auditDate),
    },
    {
      title: '状态',
      dataIndex: 'auditState',
      key: 'auditState',
      render: (state: number) => <span>{getStateStr(state)}</span>,
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      render: (state: number, item: {}) => {
        if (state === 2) {
          return (
            <a
              onClick={() => {
                editHandle(item);
              }}
            >
              修改
            </a>
          );
        }
        return '-';
      },
    },
  ];

  const Detail = () => {
    console.log('detailSource', detailSource);

    return Object.keys(detailSource).length === 0 ? (
      <div>暂无数据</div>
    ) : (
      <>
        <div className={styles['detail-state']}>
          <div>
            状态：
            <span className={styles['detail-state-error']}>
              {detailSource.auditState}
              {detailSource.reason ? `(${detailSource.reason})` : ''}
            </span>
          </div>
          <div>
            剩余修改时间：
            <span className={styles['detail-state-error']}>{detailSource.modifyTime}</span>
          </div>
        </div>

        <QuestionMsg showNextBtn={false} questionSource={detailSource} />
        {/* <div className={styles['detail-reply']}>我的回复：</div> */}
        {modalAuditState === 2 ? (
          <div>
            {detailSource.answerStandards && (
              <ReplyInput
                minWordCount={detailSource.answerStandards.lowWordCount}
                maxWordCount={detailSource.answerStandards.highWordCount}
                inputList={detailSource.answerStandards.schemeContent}
                defaultValue={detailSource.reply[0].contentList}
                onSubmit={submitEdit}
                onCancel={cancelEdit}
              />
            )}
          </div>
        ) : (
          <div className={styles['detail-reply-view']}>
            {detailSource.reply &&
              detailSource.reply[0].contentList &&
              detailSource.reply[0].contentList.map((item, index) => <p key={index}>{item}</p>)}
          </div>
        )}
      </>
    );
  };

  return (
    <div className={styles.main}>
      <StateTab tabs={tabColumns} selectTab={selectTab} defaultSelect={defaultSelect} />
      <div className={styles['time-box']}>
        <span>提交时间</span>
        <RangePicker onChange={submitTimeChange} />
      </div>
      <div className={styles['time-box']}>
        <span>审核时间</span>
        <RangePicker onChange={auditTimeChange} />
      </div>

      <ExportFormData
        action="/service/partTimerWb/topic/exportPartTimeReplyInfo"
        method="GET"
        data={{
          pid,
          type: selectState,
          beginSubTime: submitTime[0],
          endSubTime: submitTime[1],
          beginAuditTime: auditTime[0],
          endAuditTime: auditTime[1],
        }}
        columns={['标题', '积分', '提交时间', '审核时间', '状态', '操作']}
        afterRequest={({ data }: { data: [] }) => {
          const list =
            data &&
            data.map((item) => {
              const { title, score, submitDate, auditDate, auditState } = item;
              return {
                title: title.replace(/,/g, '，'),
                score,
                submitDate: formatYYMMDDHHMM(submitDate),
                auditDate: formatYYMMDDHHMM(auditDate),
                state: getStateStr(auditState),
                handle: auditState === 2 ? '修改' : '-',
              };
            });
          return list;
        }}
      />
      <Table
        dataSource={dataSource}
        loading={loading}
        columns={columns}
        pagination={{
          pageSize: 10,
          total: pageTotal,
          current: pageCurrent,
          onChange: (index, size) => {
            answerListView(index, size);
          },
        }}
      />

      <Modal
        title="答题详情"
        visible={modalVisible}
        onCancel={() => {
          setModalVisible(false);
        }}
        width={1000}
        footer={[]}
      >
        {detailLoading ? (
          <div className={styles['detail-loading']}>
            <Spin />
          </div>
        ) : (
          <Detail />
        )}
      </Modal>
    </div>
  );
};

export default connect(({ user: { currentUser } }) => ({ currentUser }))(Content);
